import { Service } from "egg";
import { Types } from "mongoose";
import { BasicFieldProps } from "../model/BasicField";
import { nanoid } from "nanoid";

export default class BasicFieldService extends Service {
  /**
   * 根据传入名称查询
   */
  public findByName(name: string) {
    return this.ctx.model.BasicField.findOne({ name }).lean();
  }

  /**
   * 查找列表
   */
  public findList() {
    return this.ctx.model.BasicField.find();
  }

  /**
   * 添加数据
   * @param data 测试数据
   */
  public async add(data) {
    const { ctx } = this;
    // TODO 暂时写死公司ID，后续需要从ctx.state.user获取
    const { user: userInfo } = ctx.state;
    const _data: Partial<BasicFieldProps> = {
      ...data,
      company_id: Types.ObjectId(userInfo.company),
    };
    return await ctx.model.BasicField.create(_data);
  }

  public fieldAdd(id, name) {
    const { ctx } = this;
    const newField = {
      name,
      id: nanoid(6),
    };
    return ctx.model.BasicField.findOneAndUpdate(
      { id },
      { $push: { fields: newField } },
      { new: true }
    ).lean();
  }
}
